package com.aimashi.railwaytoolmanagesystem.utils;

import java.util.List;

import android.content.Context;

import com.aimashi.commonlib.util.StringUtil;
import com.aimashi.railwaytoolmanagesystem.bean.GoodMode;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

/**
 * 
 * @author zhaoys
 * 
 */
public class DatabaseGoodModeUtil {
	// xutils
	private DbUtils db;

	public DatabaseGoodModeUtil(Context context) {
		db = DbUtils.create(context);
	}

	/**
	 * 向数据库中添加数�?
	 * 
	 * @param entity
	 * @throws DbException
	 */
	public void add(GoodMode entity) {
		try {
			db.save(entity);
		} catch (DbException e) {
			e.printStackTrace();
			LogUtils.i("写卡出错");
		}
	}

	/**
	 * 通过Id查找对应的GoodMode
	 * 
	 * @param id
	 *            唯一标识Id
	 * @return
	 * @throws DbException
	 */
	public GoodMode findGoodModeById(String id) {
		GoodMode entity = null;
		try {
			entity = db.findById(GoodMode.class, id); 
		} catch (DbException e) {
			LogUtils.i("查找保存epc记录出错");
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * 查找GoodMode
	 * 
	 * @return
	 * @throws DbException
	 */
	public List<GoodMode> findAllGoodModeByEndDateCount(String searchValue) {
		List<GoodMode> entity = null;
		try {
			if (!StringUtil.isNull(searchValue)) {
				entity = db.findAll(Selector.from(GoodMode.class).orderBy(
						"scanCount", true));
			} else {
				entity = db.findAll(Selector.from(GoodMode.class)
						.where("endDateCount", "like", "%" + searchValue + "%")
						.orderBy("scanCount", true));
			}
		} catch (DbException e) {
			LogUtils.i("查找记录出错");
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * 通过EpcNumber删除对应数据
	 * 
	 * @param id
	 * @throws DbException
	 */
	public void deleteGoodModeByDate(String date) {
		try {
			db.deleteById(GoodMode.class, date);
		} catch (DbException e) {
			LogUtils.i("删除记录出错");
			e.printStackTrace();
		}
	}

	public void deleteGoodModeAll() {
		try {
			db.deleteAll(GoodMode.class);
			db.dropTable(GoodMode.class);
		} catch (DbException e) {
			LogUtils.i("删除所有记录出错");
			e.printStackTrace();
		}
	}

	/**
	 * 更新记录信息
	 * 
	 * @param entity
	 *            实体
	 * @throws DbException
	 */
	public void UpdateGoodMode(GoodMode entity) {
		deleteGoodModeAll();
		add(entity);
	}

}
